iT邦幫忙

0

Day6 職訓(機器學習與資料分析工程師培訓班): PHP連接SQL

  • 分享至 

  • xImage
  •  

上午: Python程式設計

延續昨日課程,今日從流程控制開始,課程中老師也有出幾個練習題讓同學試著自己coding,都算滿簡單的練習 Python流程控制:

  1. 文字輸入&輸出: input, output
  2. 判斷式 if & else & elif . 進階→List Comprehension
  3. while迴圈 & break & continue
  4. for迴圈

下午: 人工智慧與機器學習概論

今天老師教學如何透過php連結SQL,將資料寫入DB或是從DB讀取資料:

寫入DB

<?php 
//step 1: connect db 
 if (!empty($_GET['value'])) {
    $myvalue=$_GET['value'];
} else{
	$myvalue=NULL;
}

$mysqli = new mysqli("localhost","test123","test123","aiotdb");

// Check connection
if ($mysqli -> connect_errno) {
  echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
  exit();
} else {
	print "Success! " ;
}

//step 2: sql query
if ($myvalue!=NULL){
if ($result = $mysqli -> query("insert into sensors (value) values ($myvalue)")) {
  echo "New value ". $myvalue  ." has been added.: "  ;
}else{
	echo "nothing added!";
}
}
//step 3: disconnect db
$mysqli -> close();

?>

將DB資料轉成JSON

<?php 
//step 1: connect db 

$mysqli = new mysqli("localhost","test123","test123","aiotdb");

// Check connection
if ($mysqli -> connect_errno) {
  echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
  exit();
} 

//step 2: sql query

if ($result = $mysqli -> query("select * from sensors")) {

}

//step 3: fetch array from $result
$data=[];
$index= 0;
while($row = $result -> fetch_array(MYSQLI_NUM)){
$data[$index]=$row;
$index=$index+1;
}
//step 4: ecode json
echo json_encode($data);
//step 5: disconnect db
$mysqli -> close();

?>

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言